const mysql = require('mysql');

// 创建数据池
const pool = mysql.createPool({
    host: 'gz-cynosdbmysql-grp-m6f1gzsv.sql.tencentcdb.com',
    user: 'root',
    port: '20936',
    password: 'Gundam00',
    database: 'tourism',
    connectionLimit: 1000,
    connectTimeout: 60 * 60 * 1000,
    acquireTimeout: 60 * 60 * 1000,
    timeout: 60 * 60 * 1000,
})

let query = (sql, values) => {
    console.log(sql)
    // 返回一个 Promise
    return new Promise((resolve, reject) => {
        pool.getConnection((err, connection) => {
            if (err) {
                console.log('=============================')
                console.log(err)
                reject({
                    status: false,
                    data: err
                })
            } else {
                if (values) {
                    try {
                        connection.query(sql, values, (err, rows) => {
                            if (err) {
                                reject({
                                    status: false,
                                    data: err
                                })
                                console.log(`err:${err}`);
                            } else {
                                resolve({
                                    status: true,
                                    data: rows
                                })
                            }
                            // 结束会话
                            connection.release()
                        })
                    } finally {
                        connection.release(); // 确保连接被释放
                    }
                } else {
                    try {
                        connection.query(sql, (err, rows) => {
                            if (err) {
                                reject({
                                    status: false,
                                    data: err
                                })
                                console.log(`err:${err}`);
                            } else {
                                resolve({
                                    status: true,
                                    data: rows
                                })
                            }
                            // 结束会话
                            connection.release()
                        })
                    } finally {
                        connection.release(); // 确保连接被释放
                    }
                }
            }
        })
    })
}

module.exports = query
